const express = require("express")
const path = require("path")
//引入数据库集合
const addAdvMidel = require("../db/model/addAdvModel")
const formidable = require("formidable")

//引入权限控制校验中间件
const isLoginMiddel = require("../middleware/isLoginMiddel")
const route = express.Router()
//删除管理员
route.post("/addAdv", isLoginMiddel, async (req, res) => {

    //formidable.IncomingForm方法实例化的对象可以解析formData格式的数据，实例化的时候可以传入一些配置
    const form = new formidable.IncomingForm({
        uploadDir: path.resolve(__dirname, "../upload"),
        keepExtensions: true
    });

    //解析req中携带的数据
    form.parse(req, async (err, params, file) => {
        //params就是除了文件之外的数据组成的对象
        const {
            advTitle,
            advType,
            advOrder
        } = params;
        //file就是文件的信息
        // console.log(file.advPic.newFilename);
        //添加数据库
       try {
        await addAdvMidel.create({
            advTitle,
            advType,
            advOrder,
            advHref:"/upload/"+file.advPic.newFilename,
            addTime:new Date().toLocaleString()
        })
        res.send({
            code:10000,
            msg:"添加成功",
            data:null
        })
       } catch (e) {
           res.send({
               code:10001,
               msg:"添加广告信息到服务器异常"+e.message,
               data:null
           })
       }
    })
})
module.exports = route